package com.hollowlatte.manage.config;

import com.hollowlatte.manage.shiro.CustomRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Hollow Latte
 * @date 2021/5/9 1:05
 */
@Configuration
public class ShiroConfig {
    /**
     * 1.创建自定义realm对象
     */
    @Bean
    public CustomRealm customRealm() {
        CustomRealm customRealm = new CustomRealm();
        // 修改凭证校验匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        // 设置加密算法为md5
        credentialsMatcher.setHashAlgorithmName("MD5");
        // 设置散列次数
        credentialsMatcher.setHashIterations(1024);

        customRealm.setCredentialsMatcher(credentialsMatcher);
        return customRealm;
    }

    /**
     * 2.创建安全管理器
     *
     * @return 在Web环境下一定要是DefaultWebSecurityManager，而不是SecurityManager（因为它不具有Web容器特性）
     */
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(CustomRealm realm) {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(realm);
        return manager;
    }

    /**
     * 3.创建shiroFilter
     * 负责过滤请求
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(defaultWebSecurityManager);
        // 一定要使用有序的Map，如LinkedHashMap等，否则过滤器链会出现权限紊乱的问题
        Map<String, String> map = new LinkedHashMap<>(5);

        // 配置系统公共资源
        map.put("/user/login", "anon");

        // 配置系统受限资源
        // map.put("/**", "authc");

        // 设置认证界面路径
        bean.setLoginUrl("/user/login");

        // 设置未授权页面
        // bean.setUnauthorizedUrl("/user/noauth");

        bean.setFilterChainDefinitionMap(map);
        return bean;
    }
}
